package com.yq.cp.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 緩存時間格式化工具
 *
 * @author Nico.Jiang
 * @since 2016.11.24
 */
public class TimeUtil {

    private final static Pattern p = Pattern.compile("(([0-9]+?)((d|h|mi|min|mn|s)))+?");
    private final static Integer MINUTE = 60;
    private final static Integer HOUR = 60 * MINUTE;
    private final static Integer DAY = 24 * HOUR;

    /**
     * Parse a duration
     *
     * @param duration 3h, 2mn, 7s or combination 2d4h10s, 1w2d3h10s
     * @return The number of seconds
     */
    public static int parseDuration(String duration) {
        if (duration == null) {
            return 30 * DAY;
        }
        final Matcher matcher = p.matcher(duration);
        int seconds = 0;
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid duration pattern : " + duration);
        }
        matcher.reset();
        while (matcher.find()) {
            switch (matcher.group(3)) {
                case "d":
                    seconds += Integer.parseInt(matcher.group(2)) * DAY;
                    break;
                case "h":
                    seconds += Integer.parseInt(matcher.group(2)) * HOUR;
                    break;
                case "mi":
                case "min":
                case "mn":
                    seconds += Integer.parseInt(matcher.group(2)) * MINUTE;
                    break;
                default:
                    seconds += Integer.parseInt(matcher.group(2));
                    break;
            }
        }
        return seconds;
    }

    /**
     * 獲取標準Unix時間戳
     *
     * @return
     */
    public static long getUnixTimestamp() {
        return Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
    }

    /**
     * Get timestamp.
     *
     * @return
     */
    public static String getTimestamp() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(DateTimeUtil.dqsj());
    }

}
